// Service Worker注册脚本
const origin = 'https:aimeta.huilan.com:32108/'
if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    try {
      const registration = await navigator.serviceWorker.register('sw.js');
      console.log('AI Human Models Service Worker registered:', registration);
      
      // 监听Service Worker更新
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing;
        newWorker.addEventListener('statechange', () => {
          if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
            console.log('New Service Worker available');
            // 可以在这里提示用户刷新页面
          }
        });
      });
      
      // 定期同步缓存（如果支持）
      if ('periodicSync' in registration) {
        const status = await navigator.permissions.query({
          name: 'periodic-background-sync',
        });
        
        if (status.state === 'granted') {
          await registration.periodicSync.register('clean-old-models', {
            minInterval: 24 * 60 * 60 * 1000, // 24小时
          });
        }
      }
      
    } catch (error) {
      console.error('Service Worker registration failed:', error);
    }
  });
}

// 提供清除模型缓存的工具函数
window.clearModelCache = (modelUrl) => {
  if (navigator.serviceWorker.controller) {
    navigator.serviceWorker.controller.postMessage({
      type: 'CLEAR_MODEL_CACHE',
      url: modelUrl
    });
  }
};

window.clearAllModelsCache = () => {
  if (navigator.serviceWorker.controller) {
    navigator.serviceWorker.controller.postMessage({
      type: 'CLEAR_ALL_MODELS_CACHE'
    });
  }
};

// 预加载特定模型到缓存
window.preloadModel = async (modelUrl) => {
  try {
    const response = await fetch(modelUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    console.log('Model preloaded:', modelUrl);
  } catch (error) {
    console.error('Failed to preload model:', modelUrl, error);
  }
};